package org.teremail.message;

import static java.lang.String.format;
import static java.util.regex.Pattern.compile;

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class AddressParser {

    private final static Pattern SMTP_ADDRESS = compile("<(?:[^:]*:)?([^@]*)@([^@]*)>");
    private final static Pattern POSTMASTER_ADDRESS = compile("<Postmaster(?:@([^>]*))?>");
    
    /**
     * Parses and SMTP address in the form of a forward path.  I.e. stringly
     * &lt;user@domain&gt;
     * @param addressStr
     * @return
     * @throws AddressFormatException
     */
    public static Address parseSMTP(String addressStr) throws AddressFormatException {
        
        if (addressStr == null) {
            throw new AddressFormatException("Address is null");
        }
        
        Matcher m = SMTP_ADDRESS.matcher(addressStr);
        if (m.matches() && m.groupCount() == 2) {
            String user = m.group(1);
            String domain = m.group(2);
            return new Address(user, domain);
        } else {
            String msg = format("The address '%s' is not valid", addressStr);
            throw new AddressFormatException(msg);
        }
    }

    /**
     * Parses an address string, but will first check to see if is a Postmaster
     * address.
     * 
     * @param The address as a string
     * @return
     * @throws AddressFormatException 
     */
    public static Address parseSMTPPostmaster(String addressStr) throws AddressFormatException {
        if (addressStr == null) {
            throw new AddressFormatException("Address is null");
        }
        
        Matcher m = POSTMASTER_ADDRESS.matcher(addressStr);
        if (m.matches()) {
            if (m.groupCount() == 1) {
                return new Address("Postmaster", m.group(1));
            } else {
                return new Address("Postmaster");
            }
        } else {
            return parseSMTP(addressStr);
        }
    }

}
